// js原生
    // 阻止事件冒泡
        // if(event.target==this){
        //     $(ele).fadeOut();
        // }
    // 阻止默认事件(如滚动条,禁止手机下滑拉伸页面)
        // $(window).on('touchmove', function (e) {
        //     e.preventDefault();
        // });
// url操作
    // 获取url参数
        function GetQueryString(name){
            var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if(r!=null)return  unescape(r[2]); return null;
        }
// 完整倒计时
    function countdown(eled,eleh,elem,eles,d,callback) {
        var i_day = false,i_hour = false,i_minute = false;
        var tt = setInterval(function() {
            d.s--;
            if(!d.s && !d.m && !d.h && !d.d){
                clearInterval(tt);
                callback()
            }
            if(!d.s){
                i_minute = true;
            }else if(d.s<0){
                d.s = 59;
                d.m--;
            }
            if(i_minute && !d.m){
                i_hour = true;
                i_minute = false;
            }else if(d.m<0){
                d.m = 59;
                d.h--;
            }
            if(i_hour && !d.h){
                i_day = true;
                i_hour = false;
            }else if(d.h<0){
                d.h = 23;
                d.d--;
            }
            $(eled).html(d.d)
            $(eleh).html(f(d.h))
            $(elem).html(f(d.m))
            $(eles).html(f(d.s))
        }, 1000)
    }
    function GetTimeDiff(startDate,endDate){
        var startTime = new Date(Date.parse(startDate.replace(/-/g,"/"))).getTime();
        var endTime = new Date(Date.parse(endDate.replace(/-/g,"/"))).getTime();
        var day = 1000*60*60*24,hour = 1000*60*60,minute = 1000*60;
        var days = Math.floor((endTime - startTime)/day);
        var hours = Math.floor((endTime - startTime - days*day)/hour);
        var minutes = Math.floor((endTime - startTime - days*day - hours*hour)/minute);
        var seconds = Math.floor((endTime - startTime - days*day - hours*hour - minutes*minute)/1000);
        return  {d:days,h:hours,m:minutes,s:seconds};
    }
    function f(t){
        t = t+"";
        return (t.length==1) && "0"+t || t;
    }
    // countdown(eled,eleh,elem,eles,GetTimeDiff("2017-4-10 12:00:00","2017-4-12 23:01:00"))
// 数据操作
    // 读取本地存储
        function get_data(str){
            var data = JSON.parse(localStorage.getItem(str));
            return data;
        }
    // 存入本地存储
        function set_data(data,str){
            var data_set = JSON.stringify(data);
            localStorage.setItem(str,data_set);
        }
    // 转化为数字格式
        function F(d){
            return parseFloat(d);
        }
        function I(d){
            return parseFloat(d);
        }
// 时间格式化
    // 日期格式化
        function f_t(t){
            return t.getFullYear() + "-" + f(t.getMonth()+1) + "-" + f(t.getDate()) + " " + f(t.getHours()) + ":" + f(t.getMinutes()) + ":" + f(t.getSeconds())
        }
        function f_d(t){
            return t.getFullYear() + "-" + f(t.getMonth()+1) + "-" + f(t.getDate());
        }
        function f(t){
            t = t+"";
            return (t.length==1) && "0"+t || t;
        }
// 级联操作
    // 自定义三级联动
        function level(ops){
            var data0 = {},data1 = {},data2 = {};
            for (var i=0;i<ops.data.length;i++){
                var n1 = ops.data[i];
                data0[n1.id] = {name:n1.name,lat:n1.lat,lnt:n1.lng};
                data1[n1.id] = {name:n1.name};
                data1[n1.id] = {};
                for (var j=0;j<ops.data[i].items.length;j++){
                    var n2 = ops.data[i].items[j];
                    data1[n1.id][n2.id] = {name:n2.name,lat:n2.lat,lnt:n2.lng};
                    data2[n2.id] = {name:n2.name};
                    data2[n2.id] = {};
                    if(ops.data[i].items[j].items){
                        for (var k=0;k<ops.data[i].items[j].items.length;k++){
                            var n3 = ops.data[i].items[j].items[k];
                            data2[n2.id][n3.id] = {name:n3.name,lat:n3.lat,lnt:n3.lng};
                        }
                    }
                }
            }
            var list1 = {val:ops.level1,data:data0};
            var list2 = {val:ops.level2,data:data1[ops.level1||Object.keys(data1)[0]]};
            var list3 = {val:ops.level3,data:data2[ops.level2||Object.keys(data2)[0]]};
            $(ops.ele+"1").html(ops.func(list1));
            $(ops.ele+"2").html(ops.func(list2));
            $(ops.ele+"3").html(ops.func(list3));
            $(ops.ele+"1").change(function(){
                list2.data = data1[$(this).val()];
                $(ops.ele+"2").html(ops.func(list2));
                list3.data = data2[Object.keys(list2.data)[0]];
                $(ops.ele+"3").html(ops.func(list3));
            })
            $(ops.ele+"2").change(function(){
                list3.data = data2[$(this).val()];
                $(ops.ele+"3").html(ops.func(list3));
            })
        }
    // 全国城市三级联动
        if(typeof area !== 'undefined'){
            var data_city = {},data_area = {};
            for (var i = 0; i < area.length; i++) {
                data_city[area[i].name] = {};
                data_city[area[i].name].name = area[i].name;
                data_city[area[i].name].data = {};
                for (var j = 0; j < area[i].city.length; j++) {
                    data_city[area[i].name].data[area[i].city[j].name] = area[i].city[j].name;
                    data_area[area[i].city[j].name] = {};
                    data_area[area[i].city[j].name].name = area[i].city[j].name;
                    data_area[area[i].city[j].name].data = {};
                    for (var z = 0; z < area[i].city[j].county.length; z++) {
                        data_area[area[i].city[j].name].data[area[i].city[j].county[z].name] = area[i].city[j].county[z].name;
                    }
                }
            }
        }
        function level2(ops){
            var data0 = {};
            for (var i in ops.data1){
                data0[i] = ops.data1[i].name
            }
            var list1 = {val:ops.level1,data:data0};
            var list2 = {val:ops.level2,data:ops.data1[ops.level1||Object.keys(list1.data)[0]].data};
            $(ops.ele+"1").html(ops.func(list1));
            $(ops.ele+"2").html(ops.func(list2));
            $(ops.ele+"1").change(function(){
                list2.data = ops.data1[$(this).val()].data;
                $(ops.ele+"2").html(ops.func(list2));
                if(ops.data2){
                    list3.data = ops.data2[Object.keys(list2.data)[0]].data;
                    $(ops.ele+"3").html(ops.func(list3));
                }
            })
            if(ops.data2){
                var list3 = {val:ops.level3,data:ops.data2[ops.level2||Object.keys(list2.data)[0]].data};
                $(ops.ele+"3").html(ops.func(list3));
                $(ops.ele+"2").change(function(){
                    list3.data = ops.data2[$(this).val()].data;
                    $(ops.ele+"3").html(ops.func(list3));
                })
            }
        }
// 表单提交
    // form表单的ajax提交
        // e.preventDefault();
        //有文件上传时
            // var data = new FormData($( "#form" )[0]);
            // formData .append( "", "" );
            // $.ajax({
            //     url: '' ,
            //     type: 'POST',
            //     data: data,
            //     dataType:"json",
            //     // contentType: false,
            //     // processData: false,
            //     success: function (returndata) {
            //         alert(returndata);
            //     }
            // });
        //无文件上传时
            // var data = $( "#form" ).serialize();
            // $.post("send_data.php",data,function(){

            // },"json")
    // 校验函数
        function checkone(name){
            var pattern = $(name).data("pattern");
            var tips = $(name).data("tips");
            var re = new RegExp(pattern);
            if(!name.value || name.value=="0"){
                toast("wrong",name.title+"不能为空");
                name.focus();
                return false;
            }else if(pattern && !re.test(name.value)){
                toast("wrong","格式为"+tips);
                name.focus();
                return false;
            }
            return true;
        }
        // for (var i = 0; i < this.length; i++) {
        //     if($(this[i]).attr("request")==""){
        //         if(!checkone(this[i])){
        //             return false;
        //         }
        //     }
        // }
        //submit...
    // 将表单元素转化为对象
        $.fn.serializeObject = function() {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function() {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };
    // 计算文本域剩余可输入字数
        // $("textarea").keyup(function(){
        //     var counter = $(this).val().length;
        //     $(".text_left").text(200-counter);
        // })
// doT模版
    // 载入模版
        function loadtemplate(ele,template_url,callback){
            $(ele).load(template_url,callback);
        }
    // 载入模版数据
        function loaddata(ele,func,data){
            $(ele).html(func(data));
        }
// 农户详情
    // 农户详情模版
        var evalfarmer,farmer;
        loadtemplate("#farmer_template","/template/common/farmer.html",function(){
            evalfarmer = doT.template($("#farmer_template").text());
        })
        function getfarmerinfo(n){console.log(n)
            $.post("/screen/site/farmer-detail?id="+n,{},function(res){
                res.imgs = res.pighousephoto.split("|");
                farmer = res;
                $(".farmer").show().html(evalfarmer(farmer));
                var mySwiper = new Swiper('.swiper-container',{
                    effect : 'coverflow',
                    pagination : '.swiper-pagination',
                    paginationClickable :true,
                    prevButton:'.swiper-button-prev',
                    nextButton:'.swiper-button-next',
                    loop : true
                })
            },"json")
        }
    // 弹出二维码
        function openqrcode(n){console.log(n)
            $(".pigs_list").html("<img class='all_width' src='"+farmer.pig[n].qrcode+"' onclick=\"getinfo('"+farmer.pig[n].id+"')\">")
        }
    // 品质溯源
        var pig,evalpig;
        loadtemplate("#pig_template","/template/common/pig.html",function(){
            evalpig = doT.template($("#pig_template").text());
        })
        function getinfo(n){console.log(n)
            $.post("/screen/site/pig-detail?pigid="+n,{},function(res){
                pig = res;
                $(".farmer").hide();
                $(".pig_info").show().html(evalpig(pig));
            })
        }
        function closepig(){
            $(".farmer").show();
            $(".pig_info").hide();
        }
    // 巡检记录
        var evalrecord;
        loadtemplate("#record_template","/template/common/record.html",function(){
            evalrecord = doT.template($("#record_template").text());
        })
        function getrecord(n){console.log(n)
            $.post("/screen/site/record?id="+n,{},function(res){
                $(".pig_info").html(evalrecord(res));
            })
        }
        function getshow(obj){
            $(obj).addClass("z").siblings().removeClass("z")
        }
        function closerecord(){
            $(".pig_info").html(evalpig(pig));
        }
// 加入购物车
    function addcart(t,data){
        var mycarts = get_data("cart")||{total:0,totalprice:0,totalweight:0};
        if(mycarts[data.id]){
            mycarts[data.id].num +=t;
        }else{
            mycarts[data.id] = {id:data.id,img:data.img,o_price:data.o_price,price:data.price,title:data.title,num:t,weight:data.weight,selected:1,total:data.nums};
        }
        mycarts.total +=t;
        mycarts.totalprice += data.price*t;
        mycarts.totalweight += data.weight*t;
        set_data(mycarts,"cart");
        $(".total").show().addClass("pulse").html(mycarts.total);
        setTimeout(function(){
            $(".total").removeClass("pulse")
        },3000)
    }
// 搜索框
    function loadsearchbar(callback){
        loadtemplate(".searchbar","/template/common/m_searchbar.html",function(){
            callback()
        })
    }
// 头部标题
    function loadheadbar(text,i){
        loadtemplate(".header","/template/common/m_headbar.html",function(){
            $(".header_text").html(text)
            if(!i) return false;
            $(".business_home").show().prev().hide()
        })
    }
// 底部菜单引入
    function loadfootbar(){
        loadtemplate(".foot_tab","/template/common/m_footbar.html")
    }
    function loadbfootbar(){
        loadtemplate(".foot_tab","/template/common/m_b_footbar.html")
    }
// 轮播模版引入和初始化
    function loadswipe(data,i,callback){
        loadtemplate("#swipe_template","/template/common/m_swipe.html",function(){
            var evalswipe = doT.template($("#swipe_template").text());
            loaddata(".swipe-wrap",evalswipe,data);
            swipe(callback,i);
        })
    }
    function swipe(callback,i){
        $('.swipe').Swipe({
            startSlide:i,
            auto: 0,
            callback: function(pos) {
                $('.position li').removeClass('on').eq(pos).addClass('on');
            }
        }).data('Swipe');
        var eles = $(".swipe_e");
        var h = '';
        $.each(eles,function(k,v){
            h += '<li></li>';
        })
        $(".position").html(h).children().eq(i).addClass("on");
        if(callback){
            callback()
        }
    }
// 侧边栏引入及其效果函数
    function loadsidenav(data){
        loadtemplate("#nav_template","/template/common/m_nav.html",function(){
            var evalnav = doT.template($("#nav_template").text());
            loaddata(".sidebar",evalnav,data)
        })
    }
    function togglemenu(i){
        $(".sidebar").slideToggle()
        $("body").toggleClass("row")
    }
// 产品模版引入
    function loadpro(data){
        loadtemplate("#pro_template","/template/common/m_pro.html",function(){
            evalpros = doT.template($("#pro_template").text());
            loaddata(".pros",evalpros,data)
        })
    }
// 标题列表引入
    function loadtitle(data){
        loadtemplate("#article_template","/template/common/m_article.html",function(){
            evalarticle = doT.template($("#article_template").text());
            loaddata(".lists",evalarticle,data)
        })
    }
// 文章列表引入
    function loadarticle(data){
        loadtemplate("#article_template","/template/common/m_article.html",function(){
            evalarticle = doT.template($("#article_template").text());
            loaddata(".lists",evalarticle,data)
        })
    }
// 巡检记录模版引入
    function loadinspection(data){
        loadtemplate("#inspection_template","/template/common/m_inspection.html",function(){
            var evalinspection = doT.template($("#inspection_template").text());
            loaddata(".inspection",evalinspection,data)
        })
    }
// 订单列表引入
    function loadorder(data){
        loadtemplate("#order_template","/template/common/m_order.html",function(){
            var evalorder = doT.template($("#order_template").text());
            loaddata(".order_list",evalorder,data)
        })
    }
// 农家乐订单列表引入
    function loadorder_hotel(data){
        loadtemplate("#order_template","/template/common/m_order_hotel.html",function(){
            var evalorder = doT.template($("#order_template").text());
            loaddata(".order_list",evalorder,data)
        })
    }
// 农家乐订单列表引入
    function loadorder_rasing(data){
        loadtemplate("#order_template","/template/common/m_order_rasing.html",function(){
            var evalorder = doT.template($("#order_template").text());
            loaddata(".order_list",evalorder,data)
        })
    }
// 预览图片模版引入
    function loadimg(callback){
        loadtemplate("#img_template","/template/common/m_img.html",function(){
            callback()
        })
    }
// 图片转化为base64
    function tobase64(file,callback){
        var type = file.type;
        var reader = new FileReader();
        reader.onload = function(e){
            var $tempImg = $("<img>");
            $tempImg.load(function() {
                var w = this.naturalWidth;
                if(w > 480){
                    var imgsrc = compressImg(this,type)
                }else{
                    var imgsrc = this.src;
                }
                callback(imgsrc)
            });
            $tempImg.attr("src",e.target.result);
        };
        reader.readAsDataURL(file);
    }
// 压缩图片
    function compressImg(sourceImgObj,type){
        var drawWidth = sourceImgObj.naturalWidth,
            drawHeight = sourceImgObj.naturalHeight;
        var newWidth = 480;
        var newHeight = 480*drawHeight/drawWidth;
        var cvs = document.createElement('canvas');
        var ctx = cvs.getContext("2d");
        cvs.width = newWidth;
        cvs.height = newHeight;
        ctx.drawImage(sourceImgObj, 0, 0, newWidth, newHeight);
        var newImageData = cvs.toDataURL(type, 0.5);
        return newImageData;
    }
// toast
    function toast(icon,text,callback){
        $(".toast").show();
        $(".toast").html(evalToast({icon:icon,text:text}));
        setTimeout(function(){
            $(".toast").hide();
            if(callback){
                callback()
            }
        },2000)
    }
// 上拉刷新/下拉加载更多
    (function(window) {
        'use strict';
        var mobileRefresh = function (params,callback) {
            $.extend(this.params, params);
            this._init(callback);
        }
        var touchYDelta,
            translateVal,
            firstTouchY,
            initialScroll,
            isLoading = false,
            isMoved = false;
        mobileRefresh.prototype = {
            params: {
                container: '',
                triggerDistance: 100,
                callback:false,
                type:"down"
            },
            _init : function(callback) {
                var self = this,ele = this.params.container;
                ele.addEventListener('touchstart', function(ev){
                    self.touchStart(ev)
                });
                ele.addEventListener('touchmove', function(ev){
                    self.touchMove(ev)
                });
                ele.addEventListener('touchend', function(ev){
                    self.touchEnd(ev,callback);
                });
            },
            touchStart : function(ev) {
                if (isLoading) return;
                isMoved = false,touchYDelta = '';
                var touchobj = ev.changedTouches[0];
                firstTouchY = parseInt(touchobj.clientY);
                initialScroll = this.scrollY();
            },
            touchMove : function (ev) {
                if (isLoading) {
                    ev.preventDefault();
                    return;
                }
                var self = this,
                    ele = self.params.container;
                var moving = function() {
                    var touchobj = ev.changedTouches[0],
                        touchY = parseInt(touchobj.clientY);
                        touchYDelta = touchY - firstTouchY;
                    if ( self.scrollY() === 0 && touchYDelta > 0  ) {
                        ev.preventDefault();
                    }
                    if(self.params.type =="up"){
                        if ( initialScroll < 0 || self.scrollY() >= 0 && touchYDelta > -20) {
                            firstTouchY = touchY;
                            return;
                        }
                        $(".refresh_load").show()
                        translateVal = Math.pow(-touchYDelta, 0.85);
                        $(ele).css({"transform":'translate3d(0, -' + translateVal + 'px, 0)',"transition-duration":"0ms"})
                        isMoved = true;
                        if(touchYDelta < self.params.triggerDistance){
                            $(ele).addClass("refresh_pull_up").removeClass("refresh_pull_down");
                        }else{
                            $(ele).addClass("refresh_pull_down").removeClass("refresh_pull_up");
                        }
                    }
                    if(self.params.type =="down"){console.log(touchYDelta < 0)
                        if ( initialScroll > 0 || self.scrollY() >= 0 && touchYDelta < 0) {
                            firstTouchY = touchY;
                            return;
                        }
                        translateVal = Math.pow(touchYDelta, 0.85);
                        $(ele).css({"transform":'translate3d(0, ' + translateVal + 'px, 0)',"transition-duration":"0ms"})
                        isMoved = true;
                        if(touchYDelta > self.params.triggerDistance){
                            $(ele).addClass("refresh_pull_up").removeClass("refresh_pull_down");
                        }else{
                            $(ele).addClass("refresh_pull_down").removeClass("refresh_pull_up");
                        }
                    }
                        
                };
                this.throttle(moving(), 20);
            },
            touchEnd : function (ev,callback) {
                var ele = this.params.container;
                if (isLoading|| !isMoved) {
                    isMoved = false;
                    return;
                }
                if( touchYDelta <= this.params.triggerDistance && this.params.type =="up") {
                    isLoading = true;
                    ev.preventDefault();
                    $(ele).css({"transform":'translate3d(0,-60px,0)',"transition-duration":"300ms"}).addClass("refreshing");
                    $(".refresh_load").fadeOut(2000)
                    callback();
                }
                if( touchYDelta >= this.params.triggerDistance && this.params.type =="down") {
                    isLoading = true;
                    ev.preventDefault();
                    $(ele).css({"transform":'translate3d(0,60px,0)',"transition-duration":"300ms"}).addClass("refreshing");
                    callback();
                }
                isMoved = false;
            },
            cancelLoading : function () {
                var ele = this.params.container;
                isLoading = false;
                $(ele).css("transform",'translate3d(0,0,0)').removeClass("refreshing refresh_pull_up");
            },
            scrollY : function() {
                return window.pageYOffset || window.document.documentElement.scrollTop;
            },
            throttle : function(fn, delay) {
                var allowSample = true;
                return function(e) {
                    if (allowSample) {
                        allowSample = false;
                        setTimeout(function() { allowSample = true; }, delay);
                        fn(e);
                    }
                };
            }
        }
        window.mobileRefresh = mobileRefresh;
    })(window);
